package com.acme.bankapp.service;

import com.acme.bankapp.domain.Bank;
import com.acme.bankapp.domain.Client;
import com.acme.bankapp.domain.account.Account;
import com.acme.bankapp.exception.BankException;
import com.acme.bankapp.exception.NotEnoughFundsException;

import java.io.*;

public class BankService implements Serializable {
    public static void addClient(Bank bank, Client client) throws BankException, NullPointerException{
        bank.addClient(client);
    }

    public static void modifyBank (Bank bank, double changeValue) {
        for(Client client : bank.getClients()) {
            assert client != null;
            for(Account account : client.getAccounts()) {
                assert account != null;
                if (changeValue > 0) {
                    account.deposit(changeValue);
                } else {
                    try {
                        account.withdraw(-changeValue);
                    } catch (NotEnoughFundsException e) {
                        System.out.println("Cannot withdraw " + e.getAmount() + " from account " + account + " of client " + client.getClientSalutation());
                    }
                }
            }
        }
    }

    public static void printBalance(Bank bank) {
        for (Client client : bank.getClients()) {
            assert client != null;
            client.printClientInfo();
        }
    }

    public static void saveBank(Bank bank, String fileName) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
        oos.writeObject(bank);
    }

    public static Bank loadBank(String fileName) throws IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
        Bank bank = null;
        try {
            bank = (Bank) ois.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return bank;
    }
}